package org.example.juc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 张琪
 * @date 2024/4/17 15:49
 */
public class InterruptExample {

    public static void main(String[] args) {
//        interruptTest();
//        interruptedTest();
        executorTest();
    }

    public static void interruptTest() {
        Thread t1 = new Thread(() -> {
            try {
                Thread.sleep(2000);
                System.out.println("InterruptExample.interruptTest");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t1.start();
        // 中断 处于 阻塞/限期等待/无限期等待的线程时, 会抛出InterruptException, 从而提前结束该线程
        t1.interrupt();
        System.out.println("main");
    }


    public static void interruptedTest() {
        Thread t1 = new Thread(() -> {
            // 3. 线程中断状态检测
            while (!Thread.interrupted()) {
                System.out.println("this thread is interrupted");
            }
            // 4. 跳出循环后, 线程结束
            System.out.println("thread is end");
        });
        t1.start();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 1. 先触发中断
        t1.interrupt();

        // 2. 执行外部线程
        System.out.println("main");
    }

    public static void executorTest() {
        // 1. 创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool();

        // 2. 提交任务
        executorService.execute(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("running");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        // 3. 中断线程池
        /* shutdown 会等待线程执行完成后在关闭线程池*/
//        executorService.shutdown();
        /* shutdownNow 会立刻关闭线程池*/
        executorService.shutdownNow();
        System.out.println("main");
    }
}
